/**
 * 〈所属模块〉
 * 〈功能描述〉
 *
 * @author Lcs
 * @date 2017/9/15 13:27
 */

import React, { Component } from "react";
import {
  StyleSheet, Text, View, TouchableOpacity, Image, TextInput, ScrollView,
} from "react-native";
import { connect } from "react-redux"; // 引入connect函数
import { connectActionSheet } from "@expo/react-native-action-sheet";
import * as orderInfoAction from "../actions/orderInfoAction"; // 导入action方法
import {
  Color, ScreenWidth, FontSize, scale,
} from "../common";
import LinkingUtil from "../utils/LinkingUtil";
import NavigatorUtil from "../utils/NavigatorUtil";
import BasePage from "../widget/common/BasePage";
import Button from "../widget/common/NCButton";
import StatusItem from "../widget/common/StatusItem";
import DashSecondLine from "../widget/common/DashSecondLine";
import EnumConstants from "../common/EnumConstants";
import HolderImage from "../widget/common/HolderImage";
import NetWorkUtil from "../utils/NetWorkUtil";
import { isEmpty } from "../utils/utils";

const { OrderType, OrderStatus } = EnumConstants;

let type;
let orderId;

// @connectActionSheet
class OrderInfo extends Component {
  constructor(props) {
    super(props);
    type = NavigatorUtil.getPageParam(props, "type");
    orderId = NavigatorUtil.getPageParam(props, "orderId");
  }

  componentWillMount() {
    const { props } = this;
    props.dispatch(orderInfoAction.getOrderInfo(orderId, type));
    props.dispatch(orderInfoAction.getStoreInfo());
  }

  componentWillUnmount() {
    const { props } = this;
    props.dispatch(orderInfoAction.unmount());
  }

  handleClick = () => {
    const { props } = this;
    const { orderInfoReducer } = props;
    const options = ["支付宝支付", "微信支付", "取消"];
    const cancelButtonIndex = options.length - 1;
    props.showActionSheetWithOptions(
      {
        options,
        cancelButtonIndex,
        message: "选择支付方式",
      },
      buttonIndex => {
        if (buttonIndex === 0) {
          // 支付宝支付
        } else if (buttonIndex === 1) {
          // 微信支付
        }
      },
    );
  };

  renderHeader() {
    const { props } = this;
    const { orderInfoReducer } = props;
    const { orderInfo } = orderInfoReducer;
    const { order_status, statustext, orderTypeText } = orderInfo;
    return (
      <View style={styles.headerContainer}>
        <View style={styles.headerSubContainer}>
          <HolderImage style={styles.logo} source={require("../img/ic_order_info.png")} />
          <View style={styles.headerContentContainer}>
            <Text style={styles.textHeader}>{statustext}</Text>
            <Text style={styles.textHeaderDesc}>请保持手机通话畅通哦，以免耽误您的计划和安排</Text>
          </View>
        </View>
        <View style={styles.statusContainer}>
          <View style={styles.lineContainer}>
            <DashSecondLine
              backgroundColor={order_status === OrderStatus.wait_subscribe ? Color.tab_yellow : Color.line}
              len={12}
              width={ScreenWidth / 4}
            />
            <DashSecondLine
              backgroundColor={order_status === OrderStatus.wait_delivery ? Color.tab_yellow : Color.line}
              len={12}
              width={ScreenWidth / 4}
            />
            <DashSecondLine
              backgroundColor={order_status === OrderStatus.wait_pay ? Color.tab_yellow : Color.line}
              len={12}
              width={ScreenWidth / 4}
            />
          </View>
          <StatusItem text="已提交" active={order_status === OrderStatus.wait_subscribe} logonText="1" />
          <StatusItem text="已预约" active={order_status === OrderStatus.wait_delivery} logonText="2" />
          <StatusItem text="已收货" active={order_status === OrderStatus.wait_pay} logonText="3" />
          <StatusItem text={`${orderTypeText}完成`} active={order_status === OrderStatus.end} logonText="4" />
        </View>
      </View>
    );
  }

  goAccessResultInfo = () => {
    const { props } = this;
    const { orderInfoReducer } = props;
    const { orderInfo } = orderInfoReducer;
    const {
      facility_name, facility_src, order_price, childOrderLableData,
    } = orderInfo;
    const deviceInfo = { facility_src, facility_name, brand_name: "" };
    const accessInfo = { facility_recycle_price: order_price };
    const recycleValues = [];
    for (let i = 0; i < childOrderLableData.length; i += 1) {
      const itemValue = childOrderLableData[i];
      const { lable_name, lable_id } = itemValue;
      const fIndex = recycleValues.findIndex((item, index, array) => {
        return item.lable_id === lable_id;
      });

      if (fIndex === -1) {
        recycleValues.push({ lable_name, lable_id, recycleInfo: [itemValue] });
      } else {
        const curInfoValues = recycleValues[fIndex].recycleInfo;
        curInfoValues.push(itemValue);
        recycleValues[fIndex].recycleInfo = curInfoValues;
      }
    }
    NavigatorUtil.goAccessResultInfo(deviceInfo, accessInfo, recycleValues);
  };

  renderOrderInfo() {
    const { props } = this;
    const { orderInfoReducer } = props;
    const { orderInfo } = orderInfoReducer;
    const {
      order_status,
      statustext,
      order_no,
      facility_name,
      buttonDisabled,
      buttonText,
      orderTypeText,
      showPrice,
      showTime,
      showAddress,
      wayNameText,
      wayValueText,
      serviceTypeText,
      service_name,
      service_way_expense,
      type_expense,
    } = orderInfo;
    const isUpdate = type === OrderType.UPDATE;
    const isRecycle = type === OrderType.RECYCLE;
    const isService = type === OrderType.SERVICE;
    return (
      <View style={styles.orderInfoContainer}>
        <View style={styles.orderInfoName}>
          <Text style={styles.textOrderInfo}>订单信息</Text>
          <Text style={styles.textRowValue}>{`订单编号${order_no}`}</Text>
        </View>
        <Text style={styles.deviceName}>{facility_name}</Text>
        {isService && (
          <View style={styles.itemRow}>
            <Text style={styles.textRowName}>故障详情</Text>
            <Text style={styles.textRowValue}>{service_name}</Text>
          </View>
        )}
        {!isEmpty(wayNameText) && (
          <View style={styles.itemRow}>
            <Text style={styles.textRowName}>{`${wayNameText}：`}</Text>
            <Text style={styles.textRowValue}>{serviceTypeText}</Text>
          </View>
        )}
        {isRecycle && (
          <TouchableOpacity onPress={this.goAccessResultInfo}>
            <View style={styles.itemRow}>
              <Text style={styles.textRowName}>评估详情</Text>
              <Text style={styles.textRowValue}>点击查看</Text>
              <Image source={require("../img/ic_arrow_right.png")} style={{ width: 16 * scale, height: scale * 16 }} />
            </View>
          </TouchableOpacity>
        )}
        <View style={styles.itemRow}>
          <Text style={styles.textRowName}>预约时间：</Text>
          <Text style={styles.textRowValue}>{showTime}</Text>
        </View>
        {!isUpdate && (
          <View style={styles.itemRow}>
            <Text style={styles.textRowName}>上门地址：</Text>
            <Text style={styles.textRowValue}>{showAddress}</Text>
          </View>
        )}
        {isUpdate && (
          <View style={styles.itemRow}>
            <Text style={styles.textRowName}>升级方式</Text>
            <Text style={styles.textRowValue}>{`${serviceTypeText}升级`}</Text>
          </View>
        )}
        {isService && (
          <View style={{ marginTop: scale * 10, marginLeft: scale * 16 }}>
            <Text style={styles.textAssist}>
              维修方案：
              <Text style={styles.textPrice}>{`¥${service_way_expense}`}</Text>
            </Text>
            <Text style={styles.textAssist}>
              维修方式费：
              <Text style={styles.textPrice}>{`¥${type_expense}`}</Text>
            </Text>
          </View>
        )}
        <View style={[styles.itemRowSpace, { marginTop: isService ? 0 : scale * 16 }]}>
          <Text style={styles.textAssist}>
            {`${orderTypeText}${isUpdate ? "总价" : isRecycle ? "价格" : "费"}：`}
            <Text style={styles.textPrice}>{`¥${showPrice}`}</Text>
          </Text>
          {!isEmpty(buttonText) && (
            <Button
              title={buttonText}
              buttonStyle={styles.btnContainer}
              textStyle={styles.btnText}
              onPress={this.handleClick}
            />
          )}
        </View>
      </View>
    );
  }

  renderPlaceOrerInfo() {
    const { props } = this;
    const { orderInfoReducer } = props;
    const { orderInfo } = orderInfoReducer;
    const { create_time, contactName, contactMobile } = orderInfo;
    return (
      <View style={styles.placeOrderConatiner}>
        <Text style={[styles.textOrderInfo, { marginBottom: scale * 16, marginLeft: scale * 16 }]}>下单信息</Text>
        <View style={styles.itemRow}>
          <Text style={styles.textRowName}>联系人：</Text>
          <Text style={styles.textRowValue}>{contactName}</Text>
        </View>
        <View style={styles.itemRow}>
          <Text style={styles.textRowName}>联系电话：</Text>
          <Text style={styles.textRowValue}>{contactMobile}</Text>
        </View>
        <View style={styles.itemRow}>
          <Text style={styles.textRowName}>下单时间：</Text>
          <Text style={styles.textRowValue}>{create_time}</Text>
        </View>
      </View>
    );
  }

  call = () => {
    const { props } = this;
    const options = ["呼叫", "取消"];
    const cancelButtonIndex = options.length - 1;
    const { orderInfoReducer } = props;
    const { storeInfo } = orderInfoReducer;
    const { cell_phone } = storeInfo;
    props.showActionSheetWithOptions(
      {
        options,
        cancelButtonIndex,
        message: cell_phone,
      },
      buttonIndex => {
        if (buttonIndex === 0) {
          LinkingUtil.callPhone(cell_phone);
        }
      },
    );
  };

  renderStoreInfo() {
    const { props } = this;
    const { orderInfoReducer } = props;
    const { storeInfo } = orderInfoReducer;
    const {
      platform_address, cell_phone, platform_img, online_time,
    } = storeInfo;
    return (
      <View style={styles.placeOrderConatiner}>
        <View style={styles.orderInfoName}>
          <Text style={styles.textOrderInfo}>门店地址</Text>
          <Text style={styles.textAssist}>{`服务时间：${online_time}`}</Text>
        </View>
        <View style={styles.storeInfoContainer}>
          <HolderImage
            source={
              isEmpty(platform_img)
                ? require("../img/ic_default_pic.png")
                : { uri: NetWorkUtil.getFileUrl(platform_img) }
            }
            style={styles.imageStore}
          />
          <View style={styles.storeContentContainer}>
            <Text style={styles.textStoreName}>机汇通上海总部</Text>
            <Text style={styles.textStoreAddress}>{platform_address}</Text>
          </View>
          <TouchableOpacity style={[styles.callBg, { marginRight: scale * 10 }]} onPress={this.call}>
            <View style={styles.callBg}>
              <HolderImage source={require("../img/ic_store_call.png")} style={styles.imgCall} />
            </View>
          </TouchableOpacity>
        </View>
      </View>
    );
  }

  render() {
    const { props } = this;
    const { orderInfoReducer } = props;
    const { orderInfo, loading, initing } = orderInfoReducer;

    return (
      <BasePage style={styles.container} showLoading={loading} showIniting={initing}>
        <ScrollView style={styles.container}>
          {this.renderHeader()}
          {this.renderOrderInfo()}
          {this.renderPlaceOrerInfo()}
          {this.renderStoreInfo()}
        </ScrollView>
      </BasePage>
    );
  }
}

const styles = StyleSheet.create({
  textStoreName: {
    fontSize: FontSize.SIZE_14,
    color: Color.text_title,
    fontWeight: "bold",
  },
  textStoreAddress: {
    fontSize: FontSize.SIZE_12,
    color: Color.text_desc,
    marginTop: scale * 8,
  },
  storeContentContainer: {
    flex: 1,
    paddingHorizontal: scale * 16,
    justifyContent: "center",
  },
  callBg: {
    width: scale * 40,
    height: scale * 40,
    alignItems: "center",
    justifyContent: "center",
    borderWidth: 0,
    borderRadius: scale * 20,
    backgroundColor: Color.tab_yellow,
  },
  imgCall: {
    width: scale * 24,
    height: scale * 24,
  },
  imageStore: {
    width: scale * 70,
    height: scale * 52,
  },
  storeInfoContainer: {
    width: ScreenWidth,
    marginTop: scale * 20,
    paddingHorizontal: scale * 16,
    flexDirection: "row",
    alignItems: "center",
  },
  placeOrderConatiner: {
    width: ScreenWidth,
    backgroundColor: Color.white,
    marginTop: scale * 8,
    paddingVertical: scale * 16,
  },
  btnContainer: {
    width: scale * 60,
    height: scale * 30,
    borderRadius: scale * 5,
    borderWidth: 1,
    borderColor: Color.tab_yellow,
  },
  textAssist: {
    fontSize: FontSize.SIZE_12,
    color: Color.text_assist,
  },
  btnText: {
    fontSize: FontSize.SIZE_14,
    color: Color.tab_yellow,
  },
  btnDisContainer: {
    width: scale * 60,
    height: scale * 30,
    borderRadius: scale * 5,
    borderWidth: 1,
    borderColor: Color.text_assist,
  },
  btnDisText: {
    fontSize: FontSize.SIZE_14,
    color: Color.text_assist,
  },
  orderInfoName: {
    width: ScreenWidth,
    flexDirection: "row",
    paddingHorizontal: scale * 16,
    justifyContent: "space-between",
    alignItems: "flex-end",
  },
  textOrderInfo: {
    fontSize: FontSize.SIZE_17,
    color: Color.text_title,
    fontWeight: "bold",
  },
  itemRow: {
    width: ScreenWidth,
    flexDirection: "row",
    alignItems: "center",
    paddingHorizontal: scale * 16,
    marginTop: scale * 8,
  },
  itemRowSpace: {
    width: ScreenWidth,
    flexDirection: "row",
    paddingHorizontal: scale * 16,
    marginTop: scale * 16,
    justifyContent: "space-between",
  },
  textRowName: {
    fontSize: FontSize.SIZE_12,
    color: Color.text_assist,
    width: scale * 70,
  },
  textRowValue: {
    fontSize: FontSize.SIZE_12,
    color: Color.text_desc,
  },
  textPrice: {
    fontSize: FontSize.SIZE_16,
    color: Color.text_price,
  },
  deviceName: {
    fontSize: FontSize.SIZE_14,
    color: Color.text_title,
    fontWeight: "bold",
    marginLeft: scale * 16,
    marginTop: scale * 24,
    marginBottom: scale * 6,
  },
  container: {
    flex: 1,
  },
  headerContainer: {
    width: ScreenWidth,
    alignItems: "center",
    backgroundColor: Color.white,
  },
  orderInfoContainer: {
    width: ScreenWidth,
    backgroundColor: Color.white,
    marginTop: scale * 8,
    paddingTop: scale * 24,
    paddingBottom: scale * 17,
  },
  statusContainer: {
    width: ScreenWidth,
    alignItems: "center",
    flexDirection: "row",
    marginTop: scale * 16,
    marginBottom: scale * 20,
  },
  headerSubContainer: {
    width: ScreenWidth - scale * 32,
    height: scale * 130,
    borderRadius: scale * 6,
    borderWidth: 0,
    flexDirection: "row",
    alignItems: "center",
    backgroundColor: Color.tab_yellow,
    justifyContent: "center",
  },
  headerContentContainer: {
    marginLeft: scale * 40,
  },
  logo: {
    width: scale * 56,
    height: scale * 56,
  },
  textHeader: {
    fontSize: FontSize.SIZE_18,
    color: Color.white,
    fontWeight: "bold",
  },
  textHeaderDesc: {
    width: scale * 160,
    fontSize: FontSize.SIZE_12,
    color: Color.white,
    marginTop: scale * 8,
  },
  lineContainer: {
    width: ScreenWidth,
    position: "absolute",
    flexDirection: "row",
    justifyContent: "center",
    top: scale * 16,
  },
});

const reducers = state => {
  return {
    orderInfoReducer: state.orderInfoReducer,
  };
};

export default connect(reducers)(OrderInfo);
